package com.xiang.client;

import com.xiang.handler.ClientIdleHandler;
import com.xiang.handler.ClientInbandHandler1;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

@Slf4j
public class NettyClient {

    public static void main(String[] args) {
        EventLoopGroup eventLoopGroup=new NioEventLoopGroup();
        //客户端引导类
        Bootstrap bootstrap =new Bootstrap();
        try {
            //绑定线程池
            ChannelFuture channelFuture = bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
//                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //处理服务端数据pipeline
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //header+body 固定长度编码器
                            pipeline.addLast(new LengthFieldPrepender(4));
                            //header+body 固定长度解码器
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(
                                    Integer.MAX_VALUE,//int maxFrameLength, body最大字节长度
                                    0,                //int lengthFieldOffset, length偏移量
                                    4,                //int lengthFieldLength, length字节数
                                    0,                // int lengthAdjustment, header与body间是否填充字节数
                                    4                // int initialBytesToStrip  解码后跳过字节数
                            ));

                            //二次编解码：字节--> 对象  开箱即用
                            pipeline.addLast(new StringEncoder()); //字符编码
                            pipeline.addLast(new StringDecoder()); //字符解码

//                        pipeline.addLast(new ProtobufEncoder()); //google protobuf 编码
//                        pipeline.addLast(new ProtobufDecoder(proto对象));//google protobuf 解码

                            pipeline.addLast(new ClientInbandHandler1());
                            //idle心跳
                            pipeline.addLast(new ClientIdleHandler());
                        }
                    })
                    .connect(new InetSocketAddress("127.0.0.1", 9999))
                    .sync();
            //向服务端发送数据 ByteBuf
            Channel channel = channelFuture.channel();
            ByteBuf buffer = channel.alloc().buffer(); //channel中拿ByteBuf
            buffer.writeBytes("I am NettyClient \n".getBytes(StandardCharsets.UTF_8));
            channel.writeAndFlush(buffer);

            //关闭客户端channel
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            log.error("NettyClient error:{}",e);
        }finally {
            eventLoopGroup.shutdownGracefully();
        }


    }


}
